package com.jian.sys.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jian.sys.common.*;
import com.jian.sys.pojo.Permission;
import com.jian.sys.pojo.Role;
import com.jian.sys.pojo.User;
import com.jian.sys.service.PermissionService;
import com.jian.sys.service.RoleService;
import com.jian.sys.vo.RoleVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 剑
 * @since 2020-01-13
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;
    /**
     * 查询所有和模糊查询
     */
    @RequestMapping("/loadAllRole")
    public DataGridView loadAllRole(RoleVo roleVo){

        IPage<Role> page = new Page<>(roleVo.getPage(),roleVo.getLimit());
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(roleVo.getName()),"name",roleVo.getName());
        wrapper.like(StringUtils.isNotBlank(roleVo.getRemark()),"remark",roleVo.getRemark());
        wrapper.eq(roleVo.getAvailable()!=null,"available",roleVo.getAvailable());
        wrapper.orderByDesc("createtime");
        this.roleService.page(page,wrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    /**
     * 添加角色
     * @param roleVo
     * @return
     */
    @RequestMapping("/addRole")
    public ResultObj addRole(RoleVo roleVo){
        roleVo.setCreatetime(new Date());
        System.out.println(roleVo);
        try{
            this.roleService.save(roleVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }
    /**
     * 修改角色
     * @param roleVo
     * @return
     */
    @RequestMapping("/updateRole")
    public ResultObj updateRole(RoleVo roleVo){
        try{
            this.roleService.updateById(roleVo);
            return ResultObj.UPDATE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @RequestMapping("/deleteRole")
    public ResultObj deleteRole(Integer id){
        try {
            this.roleService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 1，查询角色用户的权限
     * 2，加载所有的菜单权限树
     * @param roleId
     * @return
     */
    @RequestMapping("/queryRolePermission")
    public DataGridView queryRolePermission(Integer roleId){
        //查询所有可用的权限和菜单
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("available", Constant.AVAILABLE_TRUE);
        List<Permission> allPermissionList = this.permissionService.list(wrapper);
        //查询角色拥有的权限和菜单 pid
        List<Integer> rolePermissionList = this.roleService.queryRolePermissionByRid(roleId);
//        System.out.println(rolePermissionList);
        //给予当前角色的权限
        List<Permission>currentPermissions = null;
        if(rolePermissionList.size()>0){
            wrapper.in("id",rolePermissionList);
            currentPermissions=permissionService.list(wrapper);
        }else{
            currentPermissions=new ArrayList<>();
        }
        //返回数据格式 LIst<TreeNode>
        List<TreeNode> nodes=new ArrayList<>();
        for (Permission p1 : allPermissionList) {
            String checkArr="0";
            for (Permission p2 : currentPermissions) {
                if(p1.getId()==p2.getId()){
                    checkArr="1";
                    break;
                }
            }
            Boolean spread=(p1.getOpen()==null||p1.getOpen()==1)?true:false;
            nodes.add(new TreeNode(p1.getId(),p1.getPid(),p1.getTitle(),spread,checkArr));
        }
        return new DataGridView(nodes);
    }

    /**
     * 保存分配的权限
     * @param rid
     * @param ids
     * @return
     */
    @RequestMapping("/saveSelectPermission")
    public ResultObj saveSelectPermission(Integer rid,Integer[] ids){
        try{
            this.roleService.saveSelectPermission(rid,ids);
            return ResultObj.DISPATCH_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.DISPATCH_ERROR;
        }
    }
}

